package com.sybil.spa.controlador;

import com.sybil.spa.dominio.Usuario;
import com.sybil.spa.servicio.SolicitudServicio;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexControlador {

   @Autowired
   private SolicitudServicio solicitudServicio;

   @RequestMapping(value = "/login", method = RequestMethod.GET)
   public String formularioLogin() {
      return "usuario/login";
   }

   @RequestMapping(value = "/acerca", method = RequestMethod.GET)
   public String acerca() {
      return "comunes/acerca";
   }

   @RequestMapping(value = "/index", method = RequestMethod.GET)
   public String paginaInicio(Model model) {
      AbstractAuthenticationToken auth = (AbstractAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
      Object details = auth.getDetails();
      if (!(details instanceof HashMap)) {
         HashMap<String, Object> info = new HashMap<String, Object>();
         String usuarioActual = SecurityContextHolder.getContext().getAuthentication().getName();
         Usuario usuario = solicitudServicio.getUsuario(usuarioActual);
         info.put("nombreUsuario", usuario.getNombre());
         info.put("clave", usuario.getClave());
//         info.put("clave", "SunyerE");
         auth.setDetails(info);
      }
      HashMap<String, Object> info = (HashMap<String, Object>) SecurityContextHolder.getContext().getAuthentication().getDetails();
      String usuarioActual = (String) info.get("clave");
      model.addAttribute("solicitudes", solicitudServicio.obtenerSolicitudes(usuarioActual));
      return "index";
   }
}
